import { useAuthStore } from "@/stores/auth";
import { AxiosRequestConfig } from "axios";
import { merge } from "lodash";
import { ZAxiosOption } from ".";
import { FieldConfig } from "./config";
import { isGetMethod } from "./helpers";

export function beforeRequest(
  config: AxiosRequestConfig,
  option: Omit<ZAxiosOption, "config"> & { fieldConfig: Required<FieldConfig> }
) {
  const {
    urlPrefix,
    trailingTime,
    carryToken,
    fieldConfig: { tokenField, trailingTimeField },
  } = option;

  if (urlPrefix) {
    config.url = `${urlPrefix}${config.url}`;
  }

  const { getToken, hasToken } = useAuthStore();
  if (carryToken) {
    if (!config.headers) {
      config.headers = {};
    }
    config.headers[tokenField] = hasToken() ? getToken()! : "EMPTY_TOKEN";
  }

  if (isGetMethod(config.method)) {
    if (trailingTime) {
      if (!config.params) {
        config.params = {};
      }
      config.params[trailingTimeField] = +new Date();
    }
  } else {
    // for convenience, ${params} would be transformed to ${data} when ${config.method} is not 'GET'
    if (!config.data && config.params) {
      config.data = config.params;
      config.params = undefined;
    }
  }
  return config;
}
